package ssm.com.controler;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class UpLoadController {

    //跳转到upLoad.jsp页面
    @RequestMapping("to")
    public String to(){
        return "upLoad";
    }
    //处理上传
    @RequestMapping("toUpLoad")
    public String toUpLoad(MultipartFile fileData, Model model, HttpServletRequest request) throws IOException {
        if (fileData == null) {
            model.addAttribute("msg","请选择文件");
            return "upLoad";
        }
        //获取上传图片的名称
        String filename = fileData.getOriginalFilename();
        //System.out.println(filename);


        int index = filename.lastIndexOf('.');
        //当上传重复文件时要对文件进行重命名，否则会出错
        //文件名后缀
        String suffix = filename.substring(index);
        //拿时间(从197x年到现在的毫秒数)作文件名前缀
        long prefix = System.currentTimeMillis();

        String newFileName = prefix + suffix;

        //文件要传到哪里
        String path = "D:\\IdeaProjects\\SSM20210608\\src\\main\\webapp";

        //对path路径进行判断
        File file = new File(path);
        if (!file.exists()) {
            //创建目录
            file.mkdir();
        }
        //
        File file1 = new File(path, newFileName);

        //将来要存什么东西到数据库
        //将来可以将新的文件名存到数据库
        //上传文件
        fileData.transferTo(file1);
        model.addAttribute("msg","上传成功");


        return "upLoad";
    }
}
